using System;
using System.ComponentModel;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Microsoft.WowAddonStudio.FrameXml.Serialization.TypeConverters
{
    /// <summary>
    /// 
    /// </summary>
    public class ShadowTypeConverter : ExpandableObjectConverter
    {
        private readonly static ColorTypeConverter colorTypeConverter = new ColorTypeConverter();
        private readonly static DimensionTypeConverter dimensionTypeConverter = new DimensionTypeConverter();

        private readonly static char listSeparator = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0];
        private readonly static Regex shadowRegex = new Regex(String.Format(@"^(?<Color>[a-zA-Z]+|([01]?\d\d?|2[0-4]\d|25[0-5])\{0}([01]?\d\d?|2[0-4]\d|25[0-5])\{0}([01]?\d\d?|2[0-4]\d|25[0-5]))\s+(?<Offset>(Abs|Rel)\s+(?:[-+]?\d+(.\d+)?)\s*;\s*(?:[-+]?\d+(.\d+)?))$", listSeparator), RegexOptions.Compiled);

        /// <summary>
        /// Returns whether this converter can convert the object to the specified type, using the specified context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="destinationType">A <see cref="T:System.Type"/> that represents the type you want to convert to.</param>
        /// <returns>
        /// true if this converter can perform the conversion; otherwise, false.
        /// </returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(Shadow))
                return true;

            return base.CanConvertTo(context, destinationType);
        }

        /// <summary>
        /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="sourceType">A <see cref="T:System.Type"/> that represents the type you want to convert from.</param>
        /// <returns>
        /// true if this converter can perform the conversion; otherwise, false.
        /// </returns>
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(String))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }

        /// <summary>
        /// Converts the given value object to the specified type, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"></see> that represents the converted value.
        /// </returns>
        /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"></see>. If null is passed, the current culture is assumed. </param>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context. </param>
        /// <param name="destinationType">The <see cref="T:System.Type"></see> to convert the value parameter to. </param>
        /// <param name="value">The <see cref="T:System.Object"></see> to convert. </param>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        /// <exception cref="T:System.ArgumentNullException">The destinationType parameter is null. </exception>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if ((destinationType == typeof(String)) && (value is Shadow))
            {
                var shadow = (Shadow)value;

                string colorValue = (string)colorTypeConverter.ConvertTo(shadow.Color, typeof(string));
                string offsetValue = (string)dimensionTypeConverter.ConvertTo(shadow.Offset, typeof(string));

                return String.Format("{0} {1}", colorValue, offsetValue);    
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }

        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">
        /// The conversion cannot be performed.
        /// </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                var shadowValue = (string)value;

                if(String.IsNullOrEmpty(shadowValue))
                    return null;

                if (shadowRegex.IsMatch(shadowValue))
                {
                    var match = shadowRegex.Match(shadowValue);

                    string colorValue = match.Groups["Color"].Value;
                    string offsetValue = match.Groups["Offset"].Value;

                    Color color = (Color)colorTypeConverter.ConvertFrom(colorValue);
                    Dimension offset = (Dimension)dimensionTypeConverter.ConvertFrom(offsetValue);

                    return new Shadow { Offset = offset, Color = color };
                }

                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Invalid shadow. Use one of the following format: R{0}G{0}B Abs X{0}Y or R{0}G{0}B Rel X{0}Y or color name Abs X{0}Y or color name Rel X{0}Y", listSeparator), "value");
            }

            return base.ConvertFrom(context, culture, value);
        }
    }
}